import React from "react";
import { Layout, Menu, Dropdown, Avatar, Space, Button, Badge } from "antd";
import {
  HomeOutlined,
  BookOutlined,
  UserOutlined,
  FileTextOutlined,
  LogoutOutlined,
  BellOutlined,
  SettingOutlined,
  DashboardOutlined,
  TeamOutlined,
  ExperimentOutlined,
  BarChartOutlined,
  FolderOutlined,
  MessageOutlined,
} from "@ant-design/icons";
import { Outlet, useNavigate, useLocation } from "react-router-dom";
import { useUser } from "../contexts/UserContext";
import DigitalAssistant from "../components/DigitalAssistant/DigitalAssistant";

// 根据用户角色生成默认头像
const getDefaultAvatar = (name: string, role: string) => {
  // 使用姓名的hash值作为种子，避免中文编码问题
  const hash = name.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0);
  const seed = Math.abs(hash).toString();
  
  // 根据角色设置不同的卡通头像样式
  if (role === "teacher") {
    // 教师使用更成熟的卡通风格
    return `https://api.dicebear.com/7.x/adventurer/svg?seed=${seed}&backgroundColor=b6e3f4`;
  } else {
    // 学生使用活泼的卡通风格
    return `https://api.dicebear.com/7.x/personas/svg?seed=${seed}&backgroundColor=ffdfbf`;
  }
};

const { Header, Content, Sider } = Layout;

const TeacherLayout: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { user, logout } = useUser();

  const menuItems = [
    {
      key: "/teacher",
      icon: <HomeOutlined />,
      label: "首页",
    },
    {
      key: "/teacher/courses",
      icon: <BookOutlined />,
      label: "课程管理",
    },
    {
      key: "/teacher/preparation",
      icon: <FileTextOutlined />,
      label: "备课助手",
    },
    {
      key: "/teacher/class-management",
      icon: <TeamOutlined />,
      label: "班级管理",
    },
    {
      key: "/teacher/exam-generation",
      icon: <ExperimentOutlined />,
      label: "智能出题",
    },
    {
      key: "/teacher/exam-management",
      icon: <DashboardOutlined />,
      label: "考试管理",
    },
    {
      key: "/teacher/exam-grading",
      icon: <FileTextOutlined />,
      label: "考试批阅",
    },
    {
      key: "/teacher/homework-grading",
      icon: <FileTextOutlined />,
      label: "作业批改",
    },
    {
      key: "/teacher/learning-analysis",
      icon: <BarChartOutlined />,
      label: "学习分析",
    },
    {
      key: "/teacher/resources",
      icon: <FolderOutlined />,
      label: "教学资源",
    },
    {
      key: "/teacher/discussions",
      icon: <MessageOutlined />,
      label: "讨论区",
    },
  ];

  const handleMenuClick = (e: any) => {
    navigate(e.key);
  };

  const handleLogout = () => {
    logout();
    navigate("/login");
  };

  const dropdownItems = [
    {
      key: "profile",
      icon: <UserOutlined />,
      label: "个人资料",
      onClick: () => navigate("/teacher/profile"),
    },
    {
      key: "settings",
      icon: <SettingOutlined />,
      label: "设置",
    },
    {
      type: "divider" as const,
    },
    {
      key: "logout",
      icon: <LogoutOutlined />,
      label: "退出登录",
      onClick: handleLogout,
    },
  ];

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider
        theme="dark"
        width={240}
        style={{
          overflow: "auto",
          height: "100vh",
          position: "fixed",
          left: 0,
          top: 0,
          bottom: 0,
        }}
      >
        <div
          style={{
            height: 64,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            color: "white",
            fontSize: "18px",
            fontWeight: "bold",
            borderBottom: "1px solid #303030",
          }}
        >
          🎓 教师端
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={[location.pathname]}
          items={menuItems}
          onClick={handleMenuClick}
          style={{ borderRight: 0 }}
        />
      </Sider>

      <Layout style={{ marginLeft: 240 }}>
        <Header
          style={{
            background: "#fff",
            padding: "0 24px",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            borderBottom: "1px solid #f0f0f0",
            position: "sticky",
            top: 0,
            zIndex: 100,
          }}
        >
          <div>
            <h2 style={{ margin: 0, color: "#1890ff" }}>
              教学管理系统 - 教师端
            </h2>
          </div>

          <Space size="large">
            <Badge count={0}>
              <BellOutlined style={{ fontSize: 20, cursor: 'pointer' }} onClick={() => {
                if (user?.role === 'admin') navigate('/admin/message');
                else if (user?.role === 'teacher') navigate('/teacher/message');
                else if (user?.role === 'student') navigate('/student/message');
                else navigate('/teacher/message');
              }} />
            </Badge>
            <Dropdown
              menu={{ items: dropdownItems }}
              placement="bottomRight"
              arrow
            >
              <Space style={{ cursor: "pointer" }}>
                <Avatar 
                  size={32} 
                  src={user?.avatar || (user ? getDefaultAvatar(user.name, user.role) : undefined)}
                  icon={!(user?.avatar || (user ? getDefaultAvatar(user.name, user.role) : undefined)) ? <UserOutlined /> : undefined}
                  style={{ 
                    backgroundColor: (user?.avatar || (user ? getDefaultAvatar(user.name, user.role) : undefined)) ? 'transparent' : '#1890ff',
                    border: (user?.avatar || (user ? getDefaultAvatar(user.name, user.role) : undefined)) ? '2px solid #f0f0f0' : 'none'
                  }}
                />
                <span>{user?.name || "教师"}</span>
              </Space>
            </Dropdown>
          </Space>
        </Header>

        <Content
          style={{
            margin: "24px",
            padding: "24px",
            background: "#fff",
            borderRadius: "8px",
            minHeight: "calc(100vh - 112px)",
          }}
        >
          <Outlet />
        </Content>
      </Layout>

      {/* AI数字人助手 - 只有一个实例 */}
      <DigitalAssistant disabled={false} />
    </Layout>
  );
};

export default TeacherLayout;
